var baseurl = require('baseurl.js');
// import md5 from 'md5.js';
/**
 * 格式化日期 yyyy-MM-dd
 */
const formatDateTo = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('-');
}

/**
 * 格式化时间 yyyy-MM-dd HH:mm:ss
 */
/** 

* 时间戳转化为年 月 日 时 分 秒 

* number: 传入时间戳 

* format：返回格式，支持自定义，但参数必须与formateArr里保持一致 

*/

function formatTimeTo(number, format) {

  var formateArr = ['Y', 'M', 'D', 'h', 'm', 's'];

  var returnArr = [];

  var date = new Date(number * 1000);

  returnArr.push(date.getFullYear());

  returnArr.push(formatNumber(date.getMonth() + 1));

  returnArr.push(formatNumber(date.getDate()));

  returnArr.push(formatNumber(date.getHours()));

  returnArr.push(formatNumber(date.getMinutes()));

  returnArr.push(formatNumber(date.getSeconds()));

  for (var i in returnArr) {

    format = format.replace(formateArr[i], returnArr[i]);

  }

  return format;

}
var getCurrentTime = function () {
  return formatTime(new Date());
}

var getCurrentDate = function () {
  return formatDate(new Date());
}

var getCurrentTimestamp = function () {
  return Date.parse(new Date());
}

/**
 * 格式化数字，单数字格式为：0X
 */
const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}
/**
 * 获取基础url
 */
var getBaseUrl = function () {
  return baseurl.content;
}
// 存储至本地缓存
var setInfoToStorage = function (key, value) {
  wx.setStorageSync(key, value);
}
/**
 * 获取本地缓存内容
 */
var getInfoFromStorage = function (key) {
  try {
    return wx.getStorageSync(key);
  }
  catch (e) {
    console.log("获取" + key + "失败");
  }

  return undefined;
}
/**
 * url: 填写子url即可，例如：完整url为：http://xx.com/api/demo，则url填写为/api/demo即可，baseUrl参见util.js -> baseUrl
 * param: 请求参数
 * sendType: （需大写）有效值：OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
 * loadingType (选填)为true则显示loading，反之不显示
 * successFn: （选填）成功处理函数，若返回出错，则不执行该函数，由本方法自行处理
 * errorFn: （选填）失败处理函数，如：超时等问题，本方法已处理提示操作 
 */
var sendRequest = function (url, param, sendType, loadingType, successFn, errorFn) {
  wx.checkSession({
    success: function () {
      var token = getInfoFromStorage("token");
      var header = { 'content-type': 'application/json' };
      url = getBaseUrl() + url;
      if (loadingType) {
        wx.showLoading({
          title: "请稍后",
          mask: true
        });
      }
      wx.request({
        url: url,
        data: param,
        method: sendType,
        header: header,
        success: function (res) {
          if (loadingType) {
            wx.hideLoading();
          }
          if (successFn)
            successFn(res.data);
        },
        fail: function (res) {
          if (loadingType) {
            wx.hideLoading();
          }
          // showError("网络连接错误，请稍后重试");
          if (errorFn)
            errorFn(res.data);
        },
        complete: function () {

        }
      })
    },
    fail: function () {
    }
  })

}
/**
 * 错误提示框
 * msg: 提示内容
 */
var showError = function (msg, url) {
  wx.showModal({
    title: '提示',
    content: msg,
    showCancel: false,
    success: function () {
      if (url) {
        navigateTo(url);
      }
    }
  })
}

/**
 * 成功提示框
 */
var showSuccess = function () {
  wx.showToast({
    title: '成功',
    icon: 'success',
    duration: 2000
  })
}
/**
 * 保留当前页面，跳转到应用内的某个页面，使用wx.navigateBack可以返回到原页面。
 * url：跳转页面url
 * param： 请求参数
 * successFn: 成功处理函数（选填）
 * failFn: 失败处理函数（选填）
 * completeFn: 完成处理函数（选填）
 */
var navigateTo = function (url, param, successFn, failFn, completeFn) {
  url = setParamToUrl(url, param);
  wx.showLoading({
    title: "请稍后",
    mask: true
  });
  wx.navigateTo({
    url: url,
    success: function () {
      if (successFn)
        successFn();
    },
    fail: function () {
      console.error("页面跳转失败");
      if (failFn)
        failFn();
    },
    complete: function () {
      wx.hideLoading();
      if (completeFn)
        completeFn();
    }
  });

}

/**
 * 关闭当前页面，跳转到应用内的某个页面。
 */
var redirectTo = function (url, param, successFn, failFn, completeFn) {
  url = setParamToUrl(url, param);
  wx.showLoading({
    title: "请稍后",
    mask: true
  });
  wx.redirectTo({
    url: url,
    success: function () {
      if (successFn)
        successFn();
    },
    fail: function () {
      console.error("页面跳转失败");
      if (failFn)
        failFn();
    },
    complete: function () {
      wx.hideLoading();
      if (completeFn)
        completeFn();
    }
  });
}

/**
 * 关闭所有页面，打开到应用内的某个页面。
 */
var reLaunch = function (url, param, successFn, failFn, completeFn) {
  url = setParamToUrl(url, param);
  wx.showLoading({
    title: "请稍后",
    mask: true
  });
  wx.reLaunch({
    url: url,
    success: function () {
      if (successFn)
        successFn();
    },
    fail: function () {
      showError("网络请求超时，请稍后再试");
      if (failFn)
        failFn();
    },
    complete: function () {
      wx.hideLoading();
      if (completeFn)
        completeFn();
    }
  });
}
/**
 * 将param以get形式添加到url中
 */
var setParamToUrl = function (url, param) {
  if (param) {
    var attrArr = Object.keys(param);
    if (attrArr) {
      attrArr.forEach(function (value) {
        if (url.indexOf("?") >= 0)
          url += "&" + value + "=" + param[value];
        else
          url += "?" + value + "=" + param[value];
      });
    }
  }

  return url;
}

var setStaticUrl = function (url) {
  return baseurl.content + url;
}

/**
 * 确认框
 * option为配置对象
 */
var confirm = function (option) {
  var title = option.title ? option.title : "提示";
  var content = option.content ? option.content : "";
  var confirmText = option.confirmText ? option.confirmText : "确认";
  var cancleText = option.cancleText ? option.cancleText : "取消";
  var confirmFn = option.confirmFn ? option.confirmFn : function () { };
  var cancleFn = option.cancleFn ? option.cancleFn : function () { };
  wx.showModal({
    title: title,
    content: content,
    confirmText: confirmText,
    cancelText: cancleText,
    success: function (res) {
      if (res.confirm) {
        confirmFn(res);
      } else {
        cancleFn(res);
      }
    }
  });
}
module.exports = {
  formatDateTo: formatDateTo,
  formatTimeTo: formatTimeTo,
  formatNumber: formatNumber,
  showError: showError,
  sendRequest: sendRequest,
  showSuccess: showSuccess,
  setParamToUrl: setParamToUrl,
  // login: login,
  getInfoFromStorage: getInfoFromStorage,
  setInfoToStorage: setInfoToStorage,
  // toComplete: toComplete,
  setStaticUrl: setStaticUrl,
  navigateTo: navigateTo,
  redirectTo: redirectTo,
  // reLaunch: reLaunch,
  // uploadFile: uploadFile,
  confirm: confirm,
  // switchTab: switchTab,
  // getSessionId: getSessionId,
  // getUUID: getUUID,
  getCurrentTimestamp: getCurrentTimestamp,
  getCurrentTime: getCurrentTime,
  getCurrentDate: getCurrentDate,
  getBaseUrl: getBaseUrl,
  // uploadFile: uploadFile,
  // hxloign: hxloign
}